import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { BladeContainerBase } from "../../../../../shared/blade/blade-container-base";
import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms";
import { BladeData } from "../../../../../shared/blade/blade-data";
import { Blade } from "../../../../../shared/blade/blade.model";
import { Command } from "../../../../../shared/toolbar.service";
import { RunStop } from "../../../../../entity/run-stop.model";
import { RunStopsService } from "../../../../../service/run-stops.service";
import { Tag } from "../../../../../entity/tag.model";
@Component({
  selector: 'app-state-info-edit',
  templateUrl: './state-info-edit.component.html',
  styleUrls: ['./state-info-edit.component.css']
})
export class StateInfoEditComponent extends BladeContainerBase<RunStop> {
  @Output() clearText = new EventEmitter<boolean>();
  /**
   * 当前测点名称
   * 
   * @type {string}
   * @memberof StateInfoEditComponent
   */
  brand: string;

  /**
   * 测点名称集合
   * 
   * @type {string[]}
   * @memberof StateInfoEditComponent
   */
  tagData: string[];
  constructor(
    private fb: FormBuilder,
    private runStopsService: RunStopsService
  ) {
    super(fb)
  }

  ngOnInit() {
    if (!this.isNew) {
      this.commands = [
        new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ]

    }
    if (this.parentEntity.current.multipleValue) {
      this.tagData = this.parentEntity.tags.map(o => o.tagName);

      if (this.currentEntity.tagId) {
        let i = this.parentEntity.tags.findIndex(o => o.tagId == this.currentEntity.tagId);
        if (i > -1)
          this.brand = this.parentEntity.tags[i].tagName;
      }
    }
    super.ngOnInit();
  }
  initData(): any | Observable<any> | Promise<any> {
    this.currentEntity.unRunorStop = this.currentEntity.unRunorStop ? 1 : 0;
    this.formPatchValue(this.currentEntity);

  }
  exeSaveChange(blade: any): void {
    this.saveChange();
  }
  canSaveChange(blade: any): boolean {
    if(this.parentEntity.current.multipleValue){
      return (this.hasChange()||(this.parentEntity.tags.findIndex(o=>o&&(o.tagName==this.brand))>-1)&&this.brand!=this.currentEntity.tagName) && !this.hasError();
    }
    return this.hasChange() && !this.hasError();
  }
  exeReset(blade: any): void {
     this.brand=this.currentEntity.tagName;
    return this.formGroup.reset(this.currentEntity);
  }
  canReset(blade: any): boolean {
    if(this.parentEntity.current.multipleValue){
      return (this.hasChange()||(this.parentEntity.tags.findIndex(o=>o&&(o.tagName==this.brand))>-1)&&this.brand!=this.currentEntity.tagName) ;
    }
    return this.hasChange();
  }
  createForm() {
    let obj: {} = {
      "runStopCode": [this.currentEntity.runStopCode,
      [
        Validators.required,
        Validators.pattern("^[0-9]+$"),
        Validators.maxLength(20),
      ], (control: FormControl): any => this.runStopCodeAsnyValidator(control)
      ],
      "runStopDesc": [this.currentEntity.runStopDesc,
      [
        Validators.required,
        Validators.maxLength(20),
      ]
      ],
      "unRunorStop": [(this.currentEntity.unRunorStop ? 1 : 0),
      [
        Validators.required,
        Validators.pattern("^[01]$"),
      ]]

    };
    this.formGroup = this.fromBuider.group(obj);
  }
  runStopCodeAsnyValidator(control: FormControl) {
    if (!control.value || control.value == this.currentEntity.runStopCode) {
      return Observable.of(null);
    }
    return this.runStopsService.runStopCodeService(control.value,this.currentEntity.schemeId,  this.currentEntity.runStopId)
      .map(res => res ? { exist: true } : null);
  }
  /**
  * 设置表单错误对象
  * 
  * 
  * @memberof BladeContainerBase
  */
  setFormError(): void {
    this.formErrors = {
      "runStopCode": "",
      "runStopDesc": "",
      "unRunorStop": ""
    };
  }
  /**
  * 设置表单验证信息
  * 
  * 
  * @memberof BladeContainerBase
  */
  setValidationMessages(): void {
    this.validationMessages = {

      "runStopCode": {
        'required': '起停码不能为空。',
        'pattern': '起停码必须由数字组成。',
        'maxlength': '起停码不能多于20个字符长度。',
        "exist":"起停码已存在"
      },
      "runStopDesc": {
        'required': '起停状态不能为空。',
        'maxlength': '起停状态不能多于20个字符长度。',
      },
      "unRunorStop": {
        'required': '停止标识不能为空。',
        'pattern': '停止标识必须为1或者0。',
      }
    };
  }

  /**
   * 创建一个测点信息
   * 
   * 
   * @memberof TurbstatusEditComponent
   */
  onCreate() {
    if (!this.hasError()) {
      this.changeCurrent();
      this.runStopsService.create(this.currentEntity)
        .then(res => {
          if (res) {
            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(this.parentEntity.current);
            this.bladeService.closeBlade(this.currentBlade);
          } else {
            throw new Error("数据新增失败！")
          }
        })
        .catch(err => {
          console.log(err)
        })
        .then(res => this.bladeData.isLoading = false);

    }
  }
  /**
   * 
   * 
   * 
   * @memberof TagsEditComponent
   */
  saveChange(): any | Promise<any> | Observable<any> {

    if (this.canSaveChange(this.currentBlade)) {
      this.changeCurrent()
      return this.runStopsService.update(this.currentEntity)
        .then(res => {
          if (res) {
            this.clearText.emit(true);
            (this.parentBlade.bladeContainerInstance).refresh(this.parentEntity.current);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
          throw new Error("数据更新失败！")

        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }
  changeCurrent() {
    this.bladeData.isLoading = true;
    let formValue = this.formGroup.value;
    this.currentEntity.runStopCode = parseInt(formValue.runStopCode);
    this.currentEntity.runStopDesc = formValue.runStopDesc;
    this.currentEntity.unRunorStop = formValue.unRunorStop ? true : false;
    if (this.parentEntity.current.multipleValue) {
      let index = this.parentEntity.tags.findIndex(o => o.tagName == this.brand);
      if (index <= -1) return false;
      this.currentEntity.tagId = this.parentEntity.tags[index].tagId;
    }
  }
  filterBrands(event) {
    let tagData: string[] = [];
    for (let i = 0; i < this.parentEntity.tags.length; i++) {
      let brand: string = this.parentEntity.tags[i].tagName;
      if (brand.toLowerCase().indexOf(event.query.toLowerCase()) == 0) {
        tagData.push(brand);
      }
    }
    this.tagData = tagData;
  }

  handleDropdownClick(event) {
    setTimeout(() => {
      this.tagData = this.parentEntity.tags.map(o => o.tagName);
    }, 100)
  }
}



// WEBPACK FOOTER //
// ./src/app/module/basic/model/state-info/state-info-edit/state-info-edit.component.ts